package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuelao.yuelao_backend.entity.*;
import com.yuelao.yuelao_backend.mapper.*;
import com.yuelao.yuelao_backend.service.AchievementService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AchievementServiceImpl implements AchievementService {

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private UserTaskMapper userTaskMapper;
    
    @Resource
    private UserMapper userMapper;
    
    @Resource
    private DailyUserStatsMapper dailyUserStatsMapper;
    
    @Resource
    private UserActionLogMapper userActionLogMapper;
    
    @Resource
    private AdWatchRecordMapper adWatchRecordMapper;
    
    @Resource
    private PostMapper postMapper;
    
    @Resource
    private CommentMapper commentMapper;
    
    @Resource
    private TopicMemberMapper topicMemberMapper;
    
    @Resource
    private UserAlbumMapper userAlbumMapper;
    
    @Resource
    private UserMatchMapper userMatchMapper;
    
    @Resource
    private UserLikeMapper userLikeMapper;
    
    @Resource
    private UserFollowMapper userFollowMapper;
    
    @Resource
    private MessageMapper messageMapper;
    
    @Resource
    private GroupMessageMapper groupMessageMapper;
    
    @Resource
    private ConversationMapper conversationMapper;
    
    @Resource
    private UserVisitorMapper userVisitorMapper;
    
    @Resource
    private GroupMemberMapper groupMemberMapper;
    
    @Resource
    private InviteRecordMapper inviteRecordMapper;
    
    @Resource
    private VipOrderMapper vipOrderMapper;
    
    @Resource
    private UserCoinAccountMapper userCoinAccountMapper;
    
    @Resource
    private ShopOrderMapper shopOrderMapper;
    
    @Resource
    private CoinTransactionMapper coinTransactionMapper;
    
    @Resource
    private UserStakingMapper userStakingMapper;

    @Override
    @Transactional
    public void checkCheckinAchievements(Long userId) {
        Map<String, Long> stats = getCheckinStats(userId);
        long totalCheckinDays = stats.getOrDefault("total", 0L);
        long consecutiveCheckinDays = stats.getOrDefault("consecutive", 0L);

        checkAchievementProgress(userId, "checkin_days", totalCheckinDays);
        checkAchievementProgress(userId, "consecutive_checkin", consecutiveCheckinDays);
    }

    @Override
    @Transactional
    public void checkTaskCompletionAchievements(Long userId) {
        // For now, we assume we check this right after a daily task is completed.
        // A more robust implementation might need to calculate these stats separately.
        Map<String, Long> stats = getDailyTaskStats(userId);
        long totalDailyTasks = stats.getOrDefault("total", 0L);
        long consecutiveDailyTasks = stats.getOrDefault("consecutive", 0L);

        checkAchievementProgress(userId, "daily_task", totalDailyTasks);
        checkAchievementProgress(userId, "consecutive_daily_task", consecutiveDailyTasks);
    }

    public void checkAchievementProgress(Long userId, String keyPrefix, long currentProgress) {
        if (currentProgress <= 0) {
            return;
        }

        LambdaQueryWrapper<Task> achievementQuery = new LambdaQueryWrapper<>();
        achievementQuery.eq(Task::getType, "achievement")
                .likeRight(Task::getTaskKey, keyPrefix)
                .eq(Task::getStatus, 1);
        List<Task> achievements = taskMapper.selectList(achievementQuery);

        List<Long> achievementIds = achievements.stream().map(Task::getId).collect(Collectors.toList());
        if (achievementIds.isEmpty()) {
            return;
        }

        // 查询用户所有相关的成就记录（包括未完成的）
        LambdaQueryWrapper<UserTask> userTaskQuery = new LambdaQueryWrapper<>();
        userTaskQuery.eq(UserTask::getUserId, userId)
                .in(UserTask::getTaskId, achievementIds);
        List<UserTask> userAchievements = userTaskMapper.selectList(userTaskQuery);
        Map<Long, UserTask> userAchievementMap = userAchievements.stream()
                .collect(Collectors.toMap(UserTask::getTaskId, ua -> ua));

        for (Task achievement : achievements) {
            UserTask userTask = userAchievementMap.get(achievement.getId());
            
            if (userTask == null) {
                // 用户还没有这个成就记录，创建新记录
                userTask = new UserTask();
                userTask.setUserId(userId);
                userTask.setTaskId(achievement.getId());
                userTask.setProgress((int) currentProgress);
                userTask.setTarget(achievement.getTarget());
                userTask.setIsCompleted(currentProgress >= achievement.getTarget());
                userTask.setIsClaimed(false);
                userTask.setDate(LocalDate.now());
                userTask.setCreatedAt(LocalDateTime.now());
                userTask.setUpdatedAt(LocalDateTime.now());
                
                if (userTask.getIsCompleted()) {
                    userTask.setCompletedAt(LocalDateTime.now());
                }
                
                userTaskMapper.insert(userTask);
            } else if (!userTask.getIsCompleted()) {
                // 已有记录但未完成，更新进度
                boolean shouldUpdate = false;
                
                // 只有当进度增加时才更新
                if (currentProgress > userTask.getProgress()) {
                    userTask.setProgress((int) currentProgress);
                    shouldUpdate = true;
                }
                
                // 检查是否刚刚达成成就
                if (currentProgress >= achievement.getTarget() && !userTask.getIsCompleted()) {
                    userTask.setIsCompleted(true);
                    userTask.setCompletedAt(LocalDateTime.now());
                    shouldUpdate = true;
                }
                
                if (shouldUpdate) {
                    userTask.setUpdatedAt(LocalDateTime.now());
                    userTaskMapper.updateById(userTask);
                }
            }
            // 已完成的成就不需要更新
        }
    }

    private Map<String, Long> getCheckinStats(Long userId) {
        LambdaQueryWrapper<Task> taskQuery = new LambdaQueryWrapper<>();
        taskQuery.eq(Task::getTaskKey, "daily_checkin").eq(Task::getStatus, 1);
        Task checkinTask = taskMapper.selectOne(taskQuery);
        if (checkinTask == null) {
            return Map.of("total", 0L, "consecutive", 0L);
        }

        // Total check-ins
        LambdaQueryWrapper<UserTask> totalQuery = new LambdaQueryWrapper<>();
        totalQuery.eq(UserTask::getUserId, userId)
                .eq(UserTask::getTaskId, checkinTask.getId())
                .eq(UserTask::getIsCompleted, true);
        Long totalDays = userTaskMapper.selectCount(totalQuery);

        // Consecutive check-ins
        long consecutiveDays = 0;
        LocalDate today = LocalDate.now();
        while (true) {
            LambdaQueryWrapper<UserTask> consecutiveQuery = new LambdaQueryWrapper<>();
            consecutiveQuery.eq(UserTask::getUserId, userId)
                    .eq(UserTask::getTaskId, checkinTask.getId())
                    .eq(UserTask::getDate, today.minusDays(consecutiveDays))
                    .eq(UserTask::getIsCompleted, true);
            if (userTaskMapper.selectCount(consecutiveQuery) > 0) {
                consecutiveDays++;
            } else {
                break;
            }
        }
        return Map.of("total", totalDays, "consecutive", consecutiveDays);
    }

    private Map<String, Long> getDailyTaskStats(Long userId) {
        // This is a simplified calculation. A real implementation might need a more complex query.
        // It finds the number of distinct days the user has completed any daily task.
        
        // Find all daily task IDs
        LambdaQueryWrapper<Task> dailyTaskQuery = new LambdaQueryWrapper<>();
        dailyTaskQuery.eq(Task::getType, "daily").eq(Task::getStatus, 1);
        List<Long> dailyTaskIds = taskMapper.selectList(dailyTaskQuery).stream().map(Task::getId).collect(Collectors.toList());

        if (dailyTaskIds.isEmpty()) {
            return Map.of("total", 0L, "consecutive", 0L);
        }

        // Total days with completed daily tasks
        Long totalDays = userTaskMapper.selectCountOfDistinctDates(userId, dailyTaskIds);

        // Consecutive days with completed daily tasks
        long consecutiveDays = 0;
        LocalDate today = LocalDate.now();
        while(true) {
            if (userTaskMapper.hasCompletedDailyTaskOnDate(userId, dailyTaskIds, today.minusDays(consecutiveDays)) > 0) {
                consecutiveDays++;
            } else {
                break;
            }
        }

        return Map.of("total", totalDays, "consecutive", consecutiveDays);
    }
    
    // 活跃度类成就检查方法实现
    
    @Override
    @Transactional
    public void checkLoginAchievements(Long userId) {
        // 获取用户累计登录天数
        LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<>();
        userQuery.eq(User::getId, userId);
        User user = userMapper.selectOne(userQuery);
        if (user == null || user.getLastLoginTime() == null) {
            return;
        }
        
        // 这里简化实现，实际应该有专门的登录记录表
        // 通过用户注册时间到最后登录时间来估算登录天数
        long daysBetween = ChronoUnit.DAYS.between(user.getCreatedAt(), user.getLastLoginTime()) + 1;
        
        checkAchievementProgress(userId, "login_days", daysBetween);
        
        // 检查连续登录天数
        long consecutiveDays = calculateConsecutiveLoginDays(userId);
        checkAchievementProgress(userId, "consecutive_login", consecutiveDays);
    }
    
    @Override
    @Transactional
    public void checkActiveTimeAchievements(Long userId, int activeMinutes) {
        // 检查单日活跃时长成就
        if (activeMinutes > 0) {
            checkAchievementProgress(userId, "daily_active", activeMinutes);
        }
        
        // 获取累计活跃时长
        QueryWrapper<DailyUserStats> statsQuery = new QueryWrapper<>();
        statsQuery.eq("user_id", userId)
                .select("COALESCE(SUM(active_minutes), 0) as totalActiveMinutes");
        
        Map<String, Object> statsResult = dailyUserStatsMapper.selectMaps(statsQuery).stream()
                .findFirst().orElse(Map.of("totalActiveMinutes", 0));
        int totalActiveMinutes = ((Number) statsResult.getOrDefault("totalActiveMinutes", 0)).intValue();
        
        // 检查累计活跃时长成就
        if (totalActiveMinutes > 0) {
            checkAchievementProgress(userId, "total_active", totalActiveMinutes);
        }
    }
    
    @Override
    @Transactional
    public void checkBrowseAchievements(Long userId) {
        // 获取用户浏览动态数
        LambdaQueryWrapper<UserActionLog> browseQuery = new LambdaQueryWrapper<>();
        browseQuery.eq(UserActionLog::getUserId, userId)
                .eq(UserActionLog::getAction, "browse_post");
        
        long browsePostCount = userActionLogMapper.selectCount(browseQuery);
        checkAchievementProgress(userId, "browse_posts", (int) browsePostCount);
        
        // 获取用户浏览资料数
        LambdaQueryWrapper<UserActionLog> profileQuery = new LambdaQueryWrapper<>();
        profileQuery.eq(UserActionLog::getUserId, userId)
                .eq(UserActionLog::getAction, "browse_profile");
        
        long browseProfileCount = userActionLogMapper.selectCount(profileQuery);
        checkAchievementProgress(userId, "browse_profiles", (int) browseProfileCount);
    }
    
    @Override
    @Transactional
    public void checkProfileCompletionAchievements(Long userId, int completionPercentage) {
        // 检查资料完整度成就
        checkAchievementProgress(userId, "profile", completionPercentage);
    }
    
    @Override
    @Transactional
    public void checkWatchAdAchievements(Long userId) {
        // 获取用户观看广告次数
        LambdaQueryWrapper<AdWatchRecord> adQuery = new LambdaQueryWrapper<>();
        adQuery.eq(AdWatchRecord::getUserId, userId);
        
        long adWatchCount = adWatchRecordMapper.selectCount(adQuery);
        checkAchievementProgress(userId, "watch_ad", (int) adWatchCount);
    }
    
    // 内容创作类成就检查方法实现
    
    @Override
    @Transactional
    public void checkPostAchievements(Long userId) {
        // 获取用户发帖数量
        LambdaQueryWrapper<Post> postQuery = new LambdaQueryWrapper<>();
        postQuery.eq(Post::getUserId, userId)
                .eq(Post::getStatus, 1);
        
        long postCount = postMapper.selectCount(postQuery);
        checkAchievementProgress(userId, "post", (int) postCount);
        
        // 检查连续发帖天数
        long consecutivePostDays = calculateConsecutivePostDays(userId);
        checkAchievementProgress(userId, "consecutive_post", consecutivePostDays);
        
        // 检查热门帖子成就
        LambdaQueryWrapper<Post> popularPostQuery = new LambdaQueryWrapper<>();
        popularPostQuery.eq(Post::getUserId, userId)
                .eq(Post::getStatus, 1)
                .orderByDesc(Post::getLikeCount)
                .last("LIMIT 1");
        Post topPost = postMapper.selectOne(popularPostQuery);
        if (topPost != null && topPost.getLikeCount() != null && topPost.getLikeCount() > 0) {
            checkAchievementProgress(userId, "popular_post", topPost.getLikeCount());
        }
    }
    
    @Override
    @Transactional
    public void checkCommentAchievements(Long userId) {
        // 获取用户评论数量
        LambdaQueryWrapper<Comment> commentQuery = new LambdaQueryWrapper<>();
        commentQuery.eq(Comment::getUserId, userId)
                .eq(Comment::getStatus, 1);
        
        long commentCount = commentMapper.selectCount(commentQuery);
        checkAchievementProgress(userId, "comment", (int) commentCount);
        
        // 检查热门评论成就
        LambdaQueryWrapper<Comment> popularCommentQuery = new LambdaQueryWrapper<>();
        popularCommentQuery.eq(Comment::getUserId, userId)
                .eq(Comment::getStatus, 1)
                .orderByDesc(Comment::getLikeCount)
                .last("LIMIT 1");
        Comment topComment = commentMapper.selectOne(popularCommentQuery);
        if (topComment != null && topComment.getLikeCount() != null && topComment.getLikeCount() > 0) {
            checkAchievementProgress(userId, "popular_comment", topComment.getLikeCount());
        }
    }
    
    @Override
    @Transactional
    public void checkGetLikeAchievements(Long userId) {
        // 获取用户帖子获得的总点赞数和评论数
        QueryWrapper<Post> postQuery = new QueryWrapper<>();
        postQuery.eq("user_id", userId)
                .eq("status", 1)
                .select("COALESCE(SUM(like_count), 0) as totalLikes, COALESCE(SUM(comment_count), 0) as totalComments");
        
        Map<String, Object> result = postMapper.selectMaps(postQuery).stream().findFirst().orElse(Map.of("totalLikes", 0, "totalComments", 0));
        
        int totalLikes = ((Number) result.getOrDefault("totalLikes", 0)).intValue();
        int totalComments = ((Number) result.getOrDefault("totalComments", 0)).intValue();
        
        // 检查获得点赞成就
        if (totalLikes > 0) {
            checkAchievementProgress(userId, "get_post_like", totalLikes);
        }
        
        // 检查获得评论成就
        if (totalComments > 0) {
            checkAchievementProgress(userId, "get_comment", totalComments);
        }
    }
    
    @Override
    @Transactional
    public void checkTopicAchievements(Long userId) {
        // 获取用户加入的话题数量
        LambdaQueryWrapper<TopicMember> topicMemberQuery = new LambdaQueryWrapper<>();
        topicMemberQuery.eq(TopicMember::getUserId, userId);
        
        long topicCount = topicMemberMapper.selectCount(topicMemberQuery);
        checkAchievementProgress(userId, "join_topic", (int) topicCount);
    }
    
    @Override
    @Transactional
    public void checkAlbumAchievements(Long userId) {
        // 获取用户相册照片数量
        LambdaQueryWrapper<UserAlbum> albumQuery = new LambdaQueryWrapper<>();
        albumQuery.eq(UserAlbum::getUserId, userId)
                .eq(UserAlbum::getStatus, 1);
        
        long photoCount = userAlbumMapper.selectCount(albumQuery);
        checkAchievementProgress(userId, "upload_photo", (int) photoCount);
        
        // 检查相册完整度成就
        if (photoCount > 0) {
            checkAchievementProgress(userId, "complete_album", (int) photoCount);
        }
    }
    
    // 社交类成就检查方法实现
    
    @Override
    @Transactional
    public void checkMatchAchievements(Long userId, boolean isSuperMatch) {
        // 获取用户配对数量
        LambdaQueryWrapper<UserMatch> matchQuery = new LambdaQueryWrapper<>();
        matchQuery.and(wrapper -> wrapper
                .eq(UserMatch::getUserId1, userId)
                .or()
                .eq(UserMatch::getUserId2, userId))
                .eq(UserMatch::getStatus, 1);
        
        long matchCount = userMatchMapper.selectCount(matchQuery);
        checkAchievementProgress(userId, "match", (int) matchCount);
        
        // 检查超级配对成就
        if (isSuperMatch) {
            LambdaQueryWrapper<UserMatch> superMatchQuery = new LambdaQueryWrapper<>();
            superMatchQuery.and(wrapper -> wrapper
                    .eq(UserMatch::getUserId1, userId)
                    .or()
                    .eq(UserMatch::getUserId2, userId))
                    .eq(UserMatch::getIsSuperMatch, true)
                    .eq(UserMatch::getStatus, 1);
            
            long superMatchCount = userMatchMapper.selectCount(superMatchQuery);
            checkAchievementProgress(userId, "super_match", (int) superMatchCount);
        }
    }
    
    @Override
    @Transactional
    public void checkSendLikeAchievements(Long userId, boolean isSuperLike) {
        // 获取用户发送喜欢数量
        LambdaQueryWrapper<UserLike> likeQuery = new LambdaQueryWrapper<>();
        likeQuery.eq(UserLike::getUserId, userId)
                .eq(UserLike::getStatus, 1);
        
        long likeCount = userLikeMapper.selectCount(likeQuery);
        checkAchievementProgress(userId, "like", (int) likeCount);
        
        // 检查发送超级喜欢成就
        if (isSuperLike) {
            LambdaQueryWrapper<UserLike> superLikeQuery = new LambdaQueryWrapper<>();
            superLikeQuery.eq(UserLike::getUserId, userId)
                    .eq(UserLike::getIsSuper, true)
                    .eq(UserLike::getStatus, 1);
            
            long superLikeCount = userLikeMapper.selectCount(superLikeQuery);
            checkAchievementProgress(userId, "super_like", (int) superLikeCount);
        }
    }
    
    @Override
    @Transactional
    public void checkGetLikeFromUserAchievements(Long userId) {
        // 获取用户获得喜欢数量
        LambdaQueryWrapper<UserLike> getLikeQuery = new LambdaQueryWrapper<>();
        getLikeQuery.eq(UserLike::getLikedUserId, userId)
                .eq(UserLike::getStatus, 1);
        
        long getLikeCount = userLikeMapper.selectCount(getLikeQuery);
        checkAchievementProgress(userId, "get_like", (int) getLikeCount);
    }
    
    @Override
    @Transactional
    public void checkFollowAchievements(Long userId, boolean isFollowing) {
        if (isFollowing) {
            // 获取用户关注数量
            LambdaQueryWrapper<UserFollow> followQuery = new LambdaQueryWrapper<>();
            followQuery.eq(UserFollow::getUserId, userId)
                    .eq(UserFollow::getStatus, 1);
            
            long followCount = userFollowMapper.selectCount(followQuery);
            checkAchievementProgress(userId, "follow", (int) followCount);
        } else {
            // 获取用户被关注数量
            LambdaQueryWrapper<UserFollow> followerQuery = new LambdaQueryWrapper<>();
            followerQuery.eq(UserFollow::getFollowedUserId, userId)
                    .eq(UserFollow::getStatus, 1);
            
            long followerCount = userFollowMapper.selectCount(followerQuery);
            checkAchievementProgress(userId, "get_follower", (int) followerCount);
        }
    }
    
    @Override
    @Transactional
    public void checkMessageAchievements(Long userId, boolean isGroupMessage) {
        if (isGroupMessage) {
            // 获取用户群消息数量
            LambdaQueryWrapper<GroupMessage> groupMessageQuery = new LambdaQueryWrapper<>();
            groupMessageQuery.eq(GroupMessage::getSenderId, userId);
            
            long groupMessageCount = groupMessageMapper.selectCount(groupMessageQuery);
            checkAchievementProgress(userId, "group_message", (int) groupMessageCount);
        } else {
            // 获取用户私聊消息数量
            LambdaQueryWrapper<Message> messageQuery = new LambdaQueryWrapper<>();
            messageQuery.eq(Message::getSenderId, userId);
            
            long messageCount = messageMapper.selectCount(messageQuery);
            checkAchievementProgress(userId, "message", (int) messageCount);
            
            // 获取用户聊天对象数量
            LambdaQueryWrapper<Conversation> conversationQuery = new LambdaQueryWrapper<>();
            conversationQuery.and(wrapper -> wrapper
                    .eq(Conversation::getUserId1, userId)
                    .or()
                    .eq(Conversation::getUserId2, userId));
            
            long chatPartnerCount = conversationMapper.selectCount(conversationQuery);
            checkAchievementProgress(userId, "chat_partners", (int) chatPartnerCount);
        }
    }
    
    @Override
    @Transactional
    public void checkVisitorAchievements(Long userId, boolean isVisitor) {
        if (isVisitor) {
            // 获取用户访问他人数量
            LambdaQueryWrapper<UserActionLog> visitQuery = new LambdaQueryWrapper<>();
            visitQuery.eq(UserActionLog::getUserId, userId)
                    .eq(UserActionLog::getAction, "visit_profile");
            
            long visitCount = userActionLogMapper.selectCount(visitQuery);
            checkAchievementProgress(userId, "visit", (int) visitCount);
        } else {
            // 获取用户被访问数量
            LambdaQueryWrapper<UserVisitor> visitorQuery = new LambdaQueryWrapper<>();
            visitorQuery.eq(UserVisitor::getUserId, userId);
            
            long visitorCount = userVisitorMapper.selectCount(visitorQuery);
            checkAchievementProgress(userId, "visitor", (int) visitorCount);
        }
    }
    
    @Override
    @Transactional
    public void checkGroupAchievements(Long userId) {
        // 获取用户加入的群组数量
        LambdaQueryWrapper<GroupMember> groupMemberQuery = new LambdaQueryWrapper<>();
        groupMemberQuery.eq(GroupMember::getUserId, userId);
        
        long groupCount = groupMemberMapper.selectCount(groupMemberQuery);
        checkAchievementProgress(userId, "join_group", (int) groupCount);
    }
    
    @Override
    @Transactional
    public void checkInviteAchievements(Long userId, boolean isValidInvite) {
        // 获取用户邀请数量
        LambdaQueryWrapper<InviteRecord> inviteQuery = new LambdaQueryWrapper<>();
        inviteQuery.eq(InviteRecord::getInviterId, userId);
        
        long inviteCount = inviteRecordMapper.selectCount(inviteQuery);
        checkAchievementProgress(userId, "invite", (int) inviteCount);
        
        // 检查有效邀请成就
        if (isValidInvite) {
            LambdaQueryWrapper<InviteRecord> validInviteQuery = new LambdaQueryWrapper<>();
            validInviteQuery.eq(InviteRecord::getInviterId, userId)
                    .eq(InviteRecord::getStatus, "completed");
            
            long validInviteCount = inviteRecordMapper.selectCount(validInviteQuery);
            checkAchievementProgress(userId, "valid_invite", (int) validInviteCount);
        }
    }
    
    // VIP/消费类成就检查方法实现
    
    @Override
    @Transactional
    public void checkVipAchievements(Long userId) {
        // 获取用户VIP订单信息
        LambdaQueryWrapper<VipOrder> vipOrderQuery = new LambdaQueryWrapper<>();
        vipOrderQuery.eq(VipOrder::getUserId, userId)
                .eq(VipOrder::getStatus, 1);
        
        List<VipOrder> vipOrders = vipOrderMapper.selectList(vipOrderQuery);
        
        // 计算累计购买VIP月数
        int totalMonths = vipOrders.stream()
                .mapToInt(order -> order.getDuration() != null ? order.getDuration() : 0)
                .sum();
        
        checkAchievementProgress(userId, "vip", totalMonths);
        
        // 检查连续VIP月数
        int consecutiveMonths = calculateConsecutiveVipMonths(userId, vipOrders);
        checkAchievementProgress(userId, "consecutive_vip", consecutiveMonths);
    }
    
    @Override
    @Transactional
    public void checkCoinBalanceAchievements(Long userId, int balance) {
        // 检查爱心币余额成就
        if (balance > 0) {
            checkAchievementProgress(userId, "coin_balance", balance);
        }
    }
    
    @Override
    @Transactional
    public void checkTotalEarnedAchievements(Long userId, int totalEarned) {
        // 检查累计获得爱心币成就
        if (totalEarned > 0) {
            checkAchievementProgress(userId, "total_earned", totalEarned);
        }
    }
    
    @Override
    @Transactional
    public void checkSpendingAchievements(Long userId, int spentAmount, boolean isDaily) {
        if (isDaily) {
            // 检查单日消费成就
            if (spentAmount > 0) {
                checkAchievementProgress(userId, "daily_spent", spentAmount);
            }
        } else {
            // 获取用户累计消费金额
            LambdaQueryWrapper<UserCoinAccount> accountQuery = new LambdaQueryWrapper<>();
            accountQuery.eq(UserCoinAccount::getUserId, userId);
            UserCoinAccount account = userCoinAccountMapper.selectOne(accountQuery);
            
            if (account != null && account.getTotalSpent() != null && account.getTotalSpent() > 0) {
                checkAchievementProgress(userId, "total_spent", account.getTotalSpent());
            }
        }
    }
    
    @Override
    @Transactional
    public void checkShopPurchaseAchievements(Long userId) {
        // 获取用户商城购买次数
        LambdaQueryWrapper<ShopOrder> shopOrderQuery = new LambdaQueryWrapper<>();
        shopOrderQuery.eq(ShopOrder::getUserId, userId)
                .eq(ShopOrder::getStatus, 1);
        
        long shopPurchaseCount = shopOrderMapper.selectCount(shopOrderQuery);
        checkAchievementProgress(userId, "shop_purchase", (int) shopPurchaseCount);
    }
    
    @Override
    @Transactional
    public void checkBuyItemAchievements(Long userId) {
        // 获取用户购买道具次数
        QueryWrapper<ShopOrder> itemOrderQuery = new QueryWrapper<>();
        itemOrderQuery.eq("user_id", userId)
                .eq("status", 1)
                .select("COALESCE(SUM(quantity), 0) as totalQuantity");
        
        Map<String, Object> itemResult = shopOrderMapper.selectMaps(itemOrderQuery).stream()
                .findFirst().orElse(Map.of("totalQuantity", 0));
        int itemCount = ((Number) itemResult.getOrDefault("totalQuantity", 0)).intValue();
        
        checkAchievementProgress(userId, "buy_item", itemCount);
    }
    
    @Override
    @Transactional
    public void checkTransferAchievements(Long userId, int transferAmount) {
        // 获取用户转账次数
        LambdaQueryWrapper<CoinTransaction> transferQuery = new LambdaQueryWrapper<>();
        transferQuery.eq(CoinTransaction::getUserId, userId)
                .eq(CoinTransaction::getType, "transfer");
        
        long transferCount = coinTransactionMapper.selectCount(transferQuery);
        checkAchievementProgress(userId, "transfer", (int) transferCount);
        
        // 获取用户累计转账金额
        QueryWrapper<CoinTransaction> transferAmountQuery = new QueryWrapper<>();
        transferAmountQuery.eq("user_id", userId)
                .eq("type", "transfer")
                .select("COALESCE(SUM(amount), 0) as totalAmount");
        Map<String, Object> transferResult = coinTransactionMapper.selectMaps(transferAmountQuery).stream()
                .findFirst().orElse(Map.of("totalAmount", 0));
        int totalTransferAmount = ((Number) transferResult.getOrDefault("totalAmount", 0)).intValue();
        
        if (totalTransferAmount > 0) {
            checkAchievementProgress(userId, "transfer_amount", totalTransferAmount);
        }
    }
    
    @Override
    @Transactional
    public void checkMiningAchievements(Long userId, int earnedAmount) {
        // 检查挖矿收益成就
        if (earnedAmount > 0) {
            checkAchievementProgress(userId, "mining_earn", earnedAmount);
        }
    }
    
    @Override
    @Transactional
    public void checkStakingAchievements(Long userId) {
        // 获取用户质押次数
        LambdaQueryWrapper<UserStaking> stakingQuery = new LambdaQueryWrapper<>();
        stakingQuery.eq(UserStaking::getUserId, userId);
        
        long stakingCount = userStakingMapper.selectCount(stakingQuery);
        checkAchievementProgress(userId, "staking", (int) stakingCount);
    }
    
    @Override
    @Transactional
    public void checkLevelAchievements(Long userId, String level) {
        // 检查等级成就
        if ("Silver".equals(level)) {
            checkAchievementProgress(userId, "level", 1);
        }
        if ("Gold".equals(level)) {
            checkAchievementProgress(userId, "level", 1);
        }
        if ("Platinum".equals(level)) {
            checkAchievementProgress(userId, "level", 1);
        }
        if ("Diamond".equals(level)) {
            checkAchievementProgress(userId, "level", 1);
        }
    }
    
    // 辅助方法
    
    /**
     * 计算连续登录天数
     */
    private long calculateConsecutiveLoginDays(Long userId) {
        // 简化实现，实际应该有专门的登录记录表
        LambdaQueryWrapper<DailyUserStats> statsQuery = new LambdaQueryWrapper<>();
        statsQuery.eq(DailyUserStats::getUserId, userId)
                .orderByDesc(DailyUserStats::getDate)
                .last("LIMIT 30"); // 只检查最近30天
        
        List<DailyUserStats> statsList = dailyUserStatsMapper.selectList(statsQuery);
        
        long consecutiveDays = 0;
        LocalDate today = LocalDate.now();
        
        for (DailyUserStats stats : statsList) {
            if (stats.getDate().equals(today.minusDays(consecutiveDays)) && 
                stats.getLoginCount() != null && stats.getLoginCount() > 0) {
                consecutiveDays++;
            } else {
                break;
            }
        }
        
        return consecutiveDays;
    }
    
    /**
     * 计算连续发帖天数
     */
    private long calculateConsecutivePostDays(Long userId) {
        LambdaQueryWrapper<Post> postQuery = new LambdaQueryWrapper<>();
        postQuery.eq(Post::getUserId, userId)
                .eq(Post::getStatus, 1)
                .select(Post::getCreatedAt)
                .orderByDesc(Post::getCreatedAt);
        
        List<Post> posts = postMapper.selectList(postQuery);
        
        long consecutiveDays = 0;
        LocalDate today = LocalDate.now();
        Set<LocalDate> postDates = posts.stream()
                .map(post -> post.getCreatedAt().toLocalDate())
                .collect(Collectors.toSet());
        
        while (postDates.contains(today.minusDays(consecutiveDays))) {
            consecutiveDays++;
        }
        
        return consecutiveDays;
    }
    
    /**
     * 计算连续VIP月数
     */
    private int calculateConsecutiveVipMonths(Long userId, List<VipOrder> vipOrders) {
        // 按时间排序
        vipOrders.sort(Comparator.comparing(VipOrder::getStartTime));
        
        int consecutiveMonths = 0;
        LocalDate currentDate = LocalDate.now();
        
        for (VipOrder order : vipOrders) {
            if (order.getStartTime() != null && order.getExpireTime() != null) {
                LocalDate startTime = order.getStartTime().toLocalDate();
                LocalDate expireTime = order.getExpireTime().toLocalDate();
                
                if (expireTime.isAfter(currentDate.minusMonths(consecutiveMonths))) {
                    consecutiveMonths += order.getDuration() != null ? order.getDuration() : 0;
                }
            }
        }
        
        return consecutiveMonths;
    }
}
